package com.javajun.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.javajun.entity.SysUser;
import com.javajun.entity.UserRole;
import com.javajun.repository.SysUserRepository;

@Service
public class SysUserService implements UserDetailsService{

    @Autowired
    private SysUserRepository userDAO;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userDAO.findByUsername(username);
        if(user==null) {
            throw new UsernameNotFoundException("用户名"+username+"不存在");
        }
        List<UserRole> roles = user.getRoles();
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (UserRole role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getCode()));
        }
        return new User(user.getUsername(), user.getPassword(), authorities);
    }

}
